package com.airbat.prize.excel.core.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Excel 工具类
 *
 * @author
 */
public class ExcelUtils {

    /**
     * 将列表以 Excel 响应给前端
     *
     * @param response  响应
     * @param filename  文件名
     * @param sheetName Excel sheet 名
     * @param head      Excel head 头
     * @param data      数据列表哦
     * @param <T>       泛型，保证 head 和 data 类型的一致性
     * @throws IOException 写入失败的情况
     */
    public static <T> void write(HttpServletResponse response, String filename, String sheetName,
                                 Class<T> head, List<T> data) throws IOException {
        write(response, new LongestMatchColumnWidthStyleStrategy(), filename, sheetName, head, data);
    }

    public static <T> void write(HttpServletResponse response, WriteHandler writeHandler, String filename, String sheetName,
                                 Class<T> head, List<T> data) throws IOException {
        // 输出 Excel
        EasyExcel.write(response.getOutputStream(), head)
                .autoCloseStream(false) // 不要自动关闭，交给 Servlet 自己处理
                .registerWriteHandler(writeHandler) // 基于 column 长度，自动适配。最大 255 宽度
                .sheet(sheetName)
                .doWrite(data);
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    }

    public static <T> void write(HttpServletResponse response, WriteHandler writeHandler, String filename, String sheetName, List<T> data) throws IOException {
        ExcelWriterBuilder writerBuilder = EasyExcel.write("C:\\Users\\zj\\Desktop\\cell_by_cell_report_info.xlsx");
        writerBuilder.registerWriteHandler(writeHandler);
        ExcelWriter excelWriter = writerBuilder.build();
        WriteSheet writeSheet = new WriteSheet();
        writeSheet.setSheetName("调查表");
        excelWriter.write(data, writeSheet);
        excelWriter.finish();

        // 输出 Excel
        EasyExcel.write(response.getOutputStream())
                .autoCloseStream(false) // 不要自动关闭，交给 Servlet 自己处理
                .registerWriteHandler(writeHandler) // 基于 column 长度，自动适配。最大 255 宽度
                .sheet(sheetName)
                .doWrite(data);
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    }

    public static <T> List<T> raed(MultipartFile file, Class<T> head) throws IOException {
        return EasyExcel.read(file.getInputStream(), head, null)
                .autoCloseStream(false)  // 不要自动关闭，交给 Servlet 自己处理
                .doReadAllSync();
    }

    public static <T> List<T> raed(InputStream stream, Class<T> head) {
        return EasyExcel.read(stream, head, null)
                .autoCloseStream(false)  // 不要自动关闭，交给 Servlet 自己处理
                .doReadAllSync();
    }

    public static <T, V> void raed2(MultipartFile file, Class<T> head, List<List<T>> list, Class<V> head2, List<List<V>> list2) throws IOException {
        List<ReadSheet> readSheetList = EasyExcel.read(file.getInputStream()).build().excelExecutor().sheetList();
        if (readSheetList != null && readSheetList.size() > 0) {
            for (ReadSheet readSheet : readSheetList) {
                List<T> listTemp = new ArrayList<>();
                EasyExcel.read(file.getInputStream(), head, new ReadListener() {

                    private int rowCount = 0;

                    @Override
                    public void onException(Exception e, AnalysisContext analysisContext) {

                    }

                    @Override
                    public void invokeHead(Map map, AnalysisContext analysisContext) {

                    }

                    @Override
                    public void invoke(Object o, AnalysisContext analysisContext) {
                        rowCount++;
                        listTemp.add((T) o);
                    }

                    @Override
                    public void extra(CellExtra cellExtra, AnalysisContext analysisContext) {

                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                    }

                    @Override
                    public boolean hasNext(AnalysisContext analysisContext) {
                        if (rowCount >= 1)
                            return false;
                        else
                            return true;
                    }
                })
                        .sheet(readSheet.getSheetName())
                        .headRowNumber(2)
                        .doRead();
                list.add(listTemp);

                List<V> listTemp2 = EasyExcel.read(file.getInputStream(), head2, null)
                        .sheet(readSheet.getSheetName())
                        .headRowNumber(5)
                        .doReadSync();
                list2.add(listTemp2);
            }
        }
    }

}
